var express = require("express");
const axios = require("axios");
const cheerio = require("cheerio");
const { Document, Packer, Paragraph, TextRun } = require("docx");
const puppeteer = require("puppeteer");
const { Buffer } = require('buffer');
const fs = require("fs");
var router = express.Router();

// ================= 配置 =================
const config = {
  baseUrl: "https://www.ebay.de/itm/",
  outputFile: "/docx/",
  selector: ".d-tabs .tabs__content",
  isDynamic: false,
  requestDelay: 2000,
};

// 获取内容
router.get("/", async (req, res) => {
  res.render("index", { title: "NodeJs 爬虫控制台" });
});

/**
 * 静态页面爬取（axios + cheerio）
 */
async function fetchStaticData(url) {
  try {
    const response = await axios.get(config.baseUrl + url, {
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
        "Accept-Language": "en-US,en;q=0.9",
      },
      timeout: 10000,
    });
    const $ = cheerio.load(response.data);
    const results = [];

    $(config.selector).each((i, el) => {
      const labels = $(el)
        .find("dt")
        .map((i, dt) => $(dt).text().trim())
        .get();
      const values = $(el)
        .find("dd")
        .map((i, dd) => $(dd).text().trim())
        .get();

      const labelValuePairs = labels.map((label, index) => ({
        label,
        value: values[index] || "no value",
      }));

      results.push({
        title: $(el)
          .find(
            ".section-title .ux-layout-section-module-evo__title .ux-textspans"
          )
          .text()
          .trim(),
        labelValuePairs,
      });
    });

    return results;
  } catch (error) {
    throw new Error(`Static fetch failed: ${error.message}`);
  }
}

// 生成数据
router.post("/crawler", async (req, res) => {
  const itemId = req.body.itemId;
  try {
    let response = await fetchStaticData(itemId);
    res.render("result", {
      title: "爬取结果",
      link: config.baseUrl + itemId,
      itemId: itemId,
      result: response,
    });
  } catch (error) {
    res.render("error", {
      title: "爬取失败",
      message: "爬取失败: " + error.message,
    });
  }
});

// 下载word文档
router.post("/api/download", async (req, res) => {
  let {data, itemId} = req.body;
  try {
   let file = await generateDocx(data, itemId);
   res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
   res.setHeader('Content-Disposition', `attachment; filename="output_${itemId}.docx"`);
   res.send(file);
  } catch (error) {
    res.json({
      code: 1,
      message: "生成失败",
    });
  }
});

/**
 * 生成Word文档
 */
async function generateDocx(data) {
  // 获取详情信息内容
  const getParagraph = (labelValuePairs) => {
    return labelValuePairs.map((item) => {
      return new Paragraph({
        children: [
          new TextRun({
            text: `${item.label}:  ${item.value}`,
            color: "707070",
            size: 20,
            break: 1,
            fontFamily: "Market Sans, Arial",
            spacing: { line: 300 },
          }),
        ],
      });
    });
  };
  const getSections = () => {
    return data
      .map((item) => {
        return [
          new Paragraph({
            children: [
              new TextRun({
                text: `${item.title}`,
                bold: true,
                size: 24,
                fontFamily: "Market Sans, Arial",
                color: "000000",
              }),
            ],
          }),
          ...getParagraph(item.labelValuePairs),
        ];
      })
      .flat();
  };

  const doc = new Document({
    sections: [
      {
        properties: {},
        children: [
          new Paragraph({
            children: [
              new TextRun({
                text: "网站内容",
                bold: true,
                size: 30,
                fontFamily: "Market Sans, Arial",
                color: "2E74B5",
              }),
            ],
            alignment: "center",
            spacing: { after: 300 },
          }),
          new Paragraph({
            children: [
              new TextRun({
                text: `目标网站：${config.targetUrl}`,
                color: "000000",
                fontFamily: "Market Sans, Arial",
                size: 20,
              }),
            ],
            spacing: { after: 150 },
          }),
          ...getSections(),
        ],
      },
    ],
  });

  // 保存文件
  const buffer = await Packer.toBuffer(doc);
  // fs.writeFileSync(path, buffer);
  return buffer;
}

module.exports = router;
